package com.goldze.mvvmhabit.ui.chat;

import android.app.Application;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.support.annotation.NonNull;
import android.view.View;

import com.goldze.mvvmhabit.R;
import com.goldze.mvvmhabit.data.DemoRepository;
import com.goldze.mvvmhabit.entity.response.GetHistoryMsgResponseEntity;
import com.goldze.mvvmhabit.ui.base.viewmodel.ToolbarViewModel;
import com.goldze.mvvmhabit.utils.UserManager;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class ChatContentListViewModel extends ToolbarViewModel<DemoRepository> {

    public SingleLiveEvent requestCameraPermissions = new SingleLiveEvent<>();
    //定时器
    public Disposable mDisposableTimedTransmission = null;
    //给RecyclerView添加ItemBinding
    public ItemBinding<ChatContentListItemViewModel> itemBinding = ItemBinding.of(com.goldze.mvvmhabit.BR.viewModel, R.layout.item_chat_content_list);

    public SingleLiveEvent<Integer> rollingBottom = new SingleLiveEvent<>();

    //用户名的绑定
    public ObservableField<String> sendMsg = new ObservableField<>("");

    private boolean isRun = false;

    //给RecyclerView添加ObservableList
    public ObservableList<ChatContentListItemViewModel> observableList = new ObservableArrayList<>();
    public ObservableList<ChatContentListItemViewModel> observableListCache = new ObservableArrayList<>();

    public ChatContentListViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    /**
     * 初始化Toolbar
     */
    public void initToolbar() {
        //初始化标题栏
        setRightTextVisible(View.GONE);
        setRightIconVisible(View.GONE);
        setTitleText(UserManager.getAppManager().getGetChatUsers().getFriendName());
    }

    public void timedTransmission() {
        getHistoryMsg(true);
        if (mDisposableTimedTransmission != null) {
            mDisposableTimedTransmission.dispose();
        }
        Observable.interval(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposableTimedTransmission = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        if (isRun) {
                            isRun = true;
                            return;
                        }
                        getHistoryMsg(false);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getHistoryMsg(final Boolean isShowWait) {
        if (UserManager.getAppManager().getGetChatUsers() != null && UserManager.getAppManager().getGetChatUsers().getFriendId() != null) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            model.getHistoryMsg(UserManager.getAppManager().getGetChatUsers().getFriendId(), format.format(new Date()), "2019-08-01 00:00:00")
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            if (isShowWait) showDialog("正在请求...");
                        }
                    })
                    .subscribe(new Consumer<BaseResponse<List<GetHistoryMsgResponseEntity>>>() {
                        @Override
                        public void accept(BaseResponse<List<GetHistoryMsgResponseEntity>> response) throws Exception {
                            if (response.isSuccess()) {
                                observableListCache.clear();
                                for (GetHistoryMsgResponseEntity entity : response.getResponse()) {
                                    ChatContentListItemViewModel itemViewModel = new ChatContentListItemViewModel(ChatContentListViewModel.this, entity);
                                    //双向绑定动态添加Item
                                    observableListCache.add(itemViewModel);
                                }
                                if (!compareList(observableList, observableListCache)) {
                                    observableList.clear();
                                    observableList.addAll(observableListCache);
                                    rollingBottom.setValue(response.getResponse().size());
                                }
                            } else {
                                if (isShowWait)
                                    ToastUtils.showShort("获取聊天内容失败！");
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            if (isShowWait) dismissDialog();
                        }
                    }, new Action() {
                        @Override
                        public void run() throws Exception {
                            isRun = false;
                            if (isShowWait) dismissDialog();
                        }
                    });
        } else {
            isRun = false;
            if (isShowWait)
            ToastUtils.showShort("聊天参数异常！");
        }
    }

    private boolean compareList(List<ChatContentListItemViewModel> list1, List<ChatContentListItemViewModel> list2) {
        if (list1 == null) {
            return false;
        }
        if (list1.size() != list2.size()) {
            return false;
        }

        for (ChatContentListItemViewModel adInfoData1 : list1) {
            boolean isContains = false;
            for (ChatContentListItemViewModel adInfoData2 : list2) {
                if (adInfoData1.entity.get().getContent().contains(adInfoData2.entity.get().getContent())) {
                    isContains = true;
                    break;
                } else {
                    isContains = false;
                }
            }
            if (isContains == false) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取条目下标
     *
     * @param netWorkItemViewModel
     * @return
     */
    public int getItemPosition(ChatContentListItemViewModel mChatContentListItemViewModel) {
        return observableList.indexOf(mChatContentListItemViewModel);
    }

    public BindingCommand sendMsgOnClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (sendMsg.get().isEmpty()) {
                ToastUtils.showShort("请输入文字！");
                return;
            }
            sendMsg(sendMsg.get());
        }
    });


    public void sendMsg(String content) {
        model.sendMsg(UserManager.getAppManager().getGetChatUsers().getFriendId(), content, "0")
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        if (response.isSuccess()) {
                            sendMsg.set("");
                        } else {
                            ToastUtils.showShort("获取聊天内容失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                    }
                });
    }


    public BindingCommand selectPic = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestCameraPermissions.setValue(null);
        }
    });

    public void upLoadImageFile(String path) {
        model.uploadImg(path)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new Consumer<BaseResponse<String>>() {
                    @Override
                    public void accept(BaseResponse<String> response) throws Exception {
                        if (response.isSuccess()) {
                            sendMsg(response.getResponse());
                        } else {
                            ToastUtils.showShort("获取聊天内容失败！");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        dismissDialog();
                    }
                });
    }

}
